package com.qd.core.dblog.thread;

import com.cdqidi.exception.QueueIsEmptyException;
import com.qd.core.dblog.LogProcess;
import com.qd.system.model.OperatorLog;
import com.qd.system.service.log.OperatorLogService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProcessOperatorLogThread extends Thread {

    private final OperatorLogService operatorLogService;
    private boolean done;

    public ProcessOperatorLogThread(int idx, OperatorLogService operatorLogService) {
        super("记录操作日志" + idx);
        this.operatorLogService = operatorLogService;
    }

    private void buildDataList(List<OperatorLog> dataList) throws InterruptedException, QueueIsEmptyException {
        LogProcess.getInstance().getOperatorLogs(dataList);
    }

    @Override
    public void run() {
        log.info("{}处理线程已启动!", this.getName());
        List<OperatorLog> dataList = new ArrayList<>(5000);
        long c = 0;
        long st;
        long et = 0;
        List<OperatorLog> retryDataList = null;
        while (!done) {
            try {
                if (dataList.isEmpty()) {
                    LogProcess.getInstance().getOperatorLogs(dataList);
                }
                if (retryDataList != null) {
                    operatorLogService.saveBatch(retryDataList, retryDataList.size());
                    c += retryDataList.size();
                    retryDataList.clear();
                }
                if (!dataList.isEmpty()) {
                    try {
                        st = System.currentTimeMillis();
                        operatorLogService.saveBatch(dataList, dataList.size());
                        c += dataList.size();
                        dataList.clear();
                        et += (System.currentTimeMillis() - st);
                    } finally {
                        if (!dataList.isEmpty()) {
                            retryDataList = dataList;
                        }
                    }
                    if ((c % 2000) == 0) {
                        log.info(this.getName() + "  总计：" + c + "/" + LogProcess.getInstance().getOperatorLogSize() + "条     速度：" + (et / 2000) + "毫秒     耗时：" + et + "毫秒/2000条");
                        et = 0;
                    }
                    buildDataList(dataList);
                }
            } catch (QueueIsEmptyException ignored) {
            } catch (Throwable e) {
                log.error("e", e);
            }
        }
    }

    public void doDone() {
        done = true;
    }
}
